package com.jxwifi.cloud.quickclean.adapter;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.idroid.utils.NoDoubleClickListener;
import com.idroid.widget.CircleImageView;
import com.jxwifi.cloud.quickclean.R;
import com.jxwifi.cloud.quickclean.bean.AssemRecordsBean;
import com.jxwifi.cloud.quickclean.bean.PoiItemBean;
import com.jxwifi.cloud.quickclean.utils.TokenTimeUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class AutoPollAdapter extends RecyclerView.Adapter {

    private String TAG = this.getClass().getSimpleName();

    HashMap<String, CountDownTimer> timerMap = new HashMap<>();

    ArrayList<String> timerKeyList = new ArrayList<>();

    private OnItemClickListener mOnItemClickListener;

    private Context mContext;

    private List<AssemRecordsBean> mListBeans=new ArrayList<>();

    private long seconds;

    public AutoPollAdapter(Context context) {
        this.mContext = context;
    }

    //添加数据
    public void addData(List<AssemRecordsBean> list) {
        if (list.size() != 0 || list != null) {
            mListBeans.addAll(list);
            notifyDataSetChanged();
        }
    }

    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

         // 实例化展示的view
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.assemble_auto_poll_item, parent, false);
        // 实例化viewholder
        return new ViewHolder(view);

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
        final ViewHolder mViewHolder = (ViewHolder) viewHolder;
        final AssemRecordsBean mBeanList= mListBeans.get(position %mListBeans.size());
        if(!isDestroy((Activity)mContext)){
            if(null == mBeanList.getHeadImg()){
                Glide.with(mContext).load(R.mipmap.icon_default_head).into(mViewHolder.mImgAssemblePhoto);
            }else{
                Glide.with(mContext).load(mBeanList.getHeadImg()).into(mViewHolder.mImgAssemblePhoto);
            }
        }
        mViewHolder.mAssembleItemName.setText(mBeanList.getNickname()+",还差"+mBeanList.getDistanceNumber()+"人拼团成功");
        mViewHolder.mRelAssemblePollItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mOnItemClickListener.onItemDetailsClick(mBeanList.getCdesk(),mBeanList.getCustomerCode());
            }
        });
        mViewHolder.mTvAutoPollJoin.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                mOnItemClickListener.onItemClick(mBeanList.getCdesk(),mBeanList.getCustomerCode());
            }
        });
        try{
            SimpleDateFormat formatter   =   new   SimpleDateFormat   ("yyyy-MM-dd HH:mm");
            Date curDate =  new Date(System.currentTimeMillis());
            Date endDate = formatter.parse(mBeanList.getSurplusTime());
            seconds =endDate.getTime()-curDate.getTime();
        }catch (Exception e){

        }
        final String mCollageId = mBeanList.getId();
        String id = mBeanList.getId();
        if (!timerKeyList.contains(id)) {
            timerKeyList.add(id);
        }

        if (mViewHolder.countDownTimer != null) {
            mViewHolder.countDownTimer.cancel();
        }
        mViewHolder.countDownTimer = new CountDownTimer(seconds , 1000) {
            public void onTick(long l) {
                mViewHolder.mAssembleItemTime.setText(mBeanList.getProductName()+"拼单,剩余"+ TokenTimeUtils.getSecondToDayHourMinutes(l));
            }

            public void onFinish() {
                //倒计时结束
//                holder.timeTv.setText("00:00");
            }
        }.start();
        timerMap.put(id, mViewHolder.countDownTimer);
    }

    private String getTimeStr(long l) {
        long day = l / (1000 * 24 * 60 * 60); //单位天
        long hour = (l - day * (1000 * 24 * 60 * 60)) / (1000 * 60 * 60); //单位时
        long minute = (l - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60)) / (1000 * 60); //单位分
        long second = (l - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60) - minute * (1000 * 60)) / 1000;//单位秒

        String hourStr = String.valueOf(hour);
        if (hourStr.length() == 1) {
            hourStr = "0" + hourStr;
        }
        String minStr = String.valueOf(minute);
        if (minStr.length() == 1) {
            minStr = "0" + minStr;
        }
        String secondStr = String.valueOf(second);
        if (secondStr.length() == 1) {
            secondStr = "0" + secondStr;
        }
        //如果day为0的时候天不显示
        if (day == 0) {
            return hourStr + ":" + minStr + ":" + secondStr;
        } else {
            return day + "天" + " " + hourStr + ":" + minStr + ":" + secondStr;
        }
    }

    public void onAdapterDestroy() {
        for (int i = 0; i < timerKeyList.size(); i++) {
            if (timerKeyList.get(i) != null) {
                if (timerMap.get(timerKeyList.get(i)) != null) {
                    CountDownTimer timer = timerMap.get(timerKeyList.get(i));
                    if (timer != null) {
                        timer.cancel();
                    }
                }
            }
        }
    }


    @Override
    public int getItemCount() {
        if (mListBeans.size()<=3){
            return mListBeans.size();

        }else{
            return Integer.MAX_VALUE;
        }
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        View mContainer;
        RelativeLayout mRelAssemblePollItem;
        CircleImageView mImgAssemblePhoto;//头像
        TextView mAssembleItemName;//姓名
        TextView mAssembleItemTime;//时间
        CountDownTimer countDownTimer;
        TextView mTvAutoPollJoin;


        public ViewHolder(View itemView) {
            super(itemView);
            mContainer = itemView;
            mRelAssemblePollItem=(RelativeLayout)itemView.findViewById(R.id.rel_assemble_poll_item);
            mImgAssemblePhoto = (CircleImageView) itemView.findViewById(R.id.img_assemble_photo);
            mAssembleItemName = (TextView) itemView.findViewById(R.id.assemble_item_name);
            mAssembleItemTime=(TextView)itemView.findViewById(R.id.assemble_item_time);
            mTvAutoPollJoin=(TextView)itemView.findViewById(R.id.tv_auto_poll_join);
        }
    }

    public void setOnItemClickListener(OnItemClickListener listener) {

        this.mOnItemClickListener = listener;

    }

    public interface OnItemClickListener {

        void onItemClick(String cdesk, String customerCode);
        void onItemDetailsClick(String cdesk, String customerCode);

    }

    public static boolean isDestroy(Activity mActivity) {
        if (mActivity== null || mActivity.isFinishing() || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed())) {
            return true;
        } else {
            return false;
        }
    }
}
